#!/usr/bin/env python3

import json
import networkx as nx
from delay_detector import DelayDetector

from ryu.base import app_manager
from ryu.app.wsgi import ControllerBase, WSGIApplication, route, Response
from ryu.controller import dpset


class RestStatsApiExt(app_manager.RyuApp):
    _CONTEXTS = {
        'dpset': dpset.DPSet,
        'wsgi': WSGIApplication,
        'topo': dict,      # Shared context
        'link_delays': dict,
    }

    def __init__(self, *args, **kwargs):
        super(RestStatsApiExt, self).__init__(*args, **kwargs)
        self.dpset = kwargs['dpset']
        wsgi = kwargs['wsgi']
        self.topo = kwargs['topo']

        # self.data will be passed to controller
        self.data = {}
        if 'G' not in self.topo:
            self.topo['G'] = nx.DiGraph()
        self.data['G'] = self.topo['G']
        self.data['link_delays'] = kwargs['link_delays']

        wsgi.register(PathController, self.data)


class PathController(ControllerBase):
    def __init__(self, req, link, data, **config):
        super(PathController, self).__init__(req, link, data, **config)
        self.G = data['G']
        self.link_delays = data['link_delays']

    @route('delays', '/stats/delays', methods=['GET'])
    def get_delays(self, req, **_kwargs):
        print('***/n/n link_delays', self.link_delays)
        body = json.dumps(self.link_delays)
        return Response(content_type='application/json', body=body)

    @route('topology', '/stats/topology', methods=['GET'])
    def get_topology(self, req, **_kwargs):
        # Assuming topology data is also stored in delay_data or another shared resource
        graph_data = nx.readwrite.json_graph.node_link_data(self.G)
        body = json.dumps(graph_data)
        return Response(content_type='application/json', body=body)

